package cn.edu.jdbc;

import cn.edu.jdbc.util.JdbcUtil;

import java.sql.*;
import java.util.Scanner;

/**
 * 防止SQL注入攻击：
 * PreparedStatement
 */
public class JdbcDemo11 {
    public static void main(String[] args) {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            conn = JdbcUtil.getConn();
            //TODO...
            String sql = "select * from mydb01 where username=? and password = ?";
            ps = conn.prepareStatement(sql);
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入用户名：");
            String un = sc.nextLine();
            System.out.println("请输入密码：");
            String pwd = sc.nextLine();

            /*设置参数 ?对应的值
                ?是整数的话，ps.setInt(...);
                ?是字符串的话，ps.setString(...);
             */
            ps.setString(1, un);
            ps.setString(2, pwd);

            rs = ps.executeQuery();
            if (rs.next()){
                String nickname = rs.getString("nickname");
                System.out.println(nickname + "登录成功~~~");
            } else {
                System.out.println("用户名或者密码错误~~");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(rs, ps, conn);
        }
    }
}
